package com.bite.friend.manager;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.redis.service.RedisService;
import com.bite.common.core.constants.CacheConstants;
import com.bite.friend.domain.user.User;
import com.bite.friend.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;


    public User getByUserId(Long userId) {
        if (userId == null) return null;
        String userKey = getUserKey(userId);
        User user = redisService.getCacheObject(userKey, User.class);
        if (user == null) {
            user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .select(User::getUserId,
                            User::getAvatar,
                            User::getNickName,
                            User::getPhone,
                            User::getWechat,
                            User::getEmail,
                            User::getSchoolName,
                            User::getMajorName,
                            User::getIntroduce,
                            User::getSex,
                            User::getStatus
                    )
                    .eq(User::getUserId, userId));
            refreshUser(user);
        }
        return user;
    }

    public void refreshUser(User user) {
        String userKey = getUserKey(user.getUserId());
        redisService.setCacheObject(userKey, user, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }


    private String getUserKey(Long userId) {
        return CacheConstants.USER_DETAIL + userId;
    }
}
